#include "udpconfigdialog.h"
#include <QFormLayout>
#include <QRegExpValidator>

UDPConfigDialog::UDPConfigDialog(QString ip, int port, QWidget *parent)
    : QDialog(parent), ip(ip), port(port)
{
    initUI();
}

void UDPConfigDialog::initUI()
{
    QFormLayout *layout = new QFormLayout;
    ipLabel = new QLabel(tr("&IP: "));
    portLabel = new QLabel(tr("&Port"));

    ipEdit = new QLineEdit;
    portEdit = new QLineEdit;

    ipEdit->setText(ip);
    QRegExp rx("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$");
    QRegExpValidator *mIP = new QRegExpValidator(rx, this);
    ipEdit->setValidator(mIP);
    ipEdit->setEnabled(false);

    portEdit->setText(QString::number(port));
    portEdit->setValidator(new QRegExpValidator(QRegExp("[0-9]+$")));

    okBtn = new QPushButton(tr("OK"));
    cancelBtn = new QPushButton(tr("Cancel"));

    layout->addRow(ipLabel, ipEdit);
    layout->addRow(portLabel, portEdit);
    layout->addRow(okBtn, cancelBtn);

    connect(okBtn, &QAbstractButton::clicked, this, &QDialog::accept);
    connect(cancelBtn, &QAbstractButton::clicked, this, &QDialog::reject);
    setLayout(layout);
}

void UDPConfigDialog::getData(QMap<QString, QString> &config)
{
    config.insert("IP", ipEdit->text());
    config.insert("PORT", portEdit->text());
}

QString UDPConfigDialog::getIP()
{
    return ipEdit->text();
}
